<?php

namespace App\Models;

class Action extends Base
{
    const STATUS_BEGIN       = 1; //启用
    const STATUS_STOP        = 2; //申请审核

    const IS_DESPLAY         = 1; //显示
    const NO_DESPLAY         = 1; //显示

    const LEVEL_MODULE       = 1; //模块
    const LEVEL_ACTION       = 2; //权限

    protected $table = 'wd_system_action';

    public function ActionList($actionids = '') {

        $list = $this->orderBy('displayorder','asc')->get()->toArray();

        if ($actionids != '') {

            $actionArr = explode(',', $actionids);

            foreach ($list as &$value) {
                $value['check'] = in_array($value['id'], $actionArr) ? true : false;
            }
        }
        return $this->getSort($list);
    }

    /**
     * 获得菜单
     */
    public function getMenu($data = []) 
    {
        if (empty($data)) {

            $data = $this->where('status', self::STATUS_BEGIN)->where('display', self::IS_DESPLAY)->get();
        }

        return $this->getSort($data);
    } 

    /**
     * 递归获得权限分类
     * @return [type] [description]
     */
    private function getSort($data) {

        $pArr = $this->getPAction($data);

        $result = $this->getSAction($pArr, $data);

        return $result;
    }

    /**
     * 递归获得子类
     * @param  [type] $pArr [description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    private function getSAction($pArr, $data) {

        foreach ($pArr as &$value) {
            $value['son'] = $this->getPAction($data, $value['id']);
            if (!empty($value['son'])) {
                $value['son'] = $this->getSAction($value['son'], $data);
            } else {
                unset($value['son']);
            }
        }
        return $pArr;
    }

    /**
     * 获得指定父类id的数据
     * @param  [type]  $data [description]
     * @param  integer $pid  [description]
     * @return [type]        [description]
     */
    private function getPAction($data, $pid = 0) {

        $arr = [];

        foreach ($data as $key => $value) {
            ($value['pid'] == $pid ) && $arr[] = $value;
        }

        return $arr;
    }
}
